package com.air.ota.service.imp;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.air.common.service.imp.BaseServiceImp;
import com.air.common.util.QueryCondition;
import com.air.common.util.QueryExpression;
import com.air.ota.dao.PkgSequenceDao;
import com.air.ota.mo.PkgSequence;
import com.air.ota.service.IPkgSequenceService;
import com.air.ota.util.HexStringUtil;

@Service("pkgSequenceService")
public class PkgSequenceServiceImp extends BaseServiceImp implements
		IPkgSequenceService, InitializingBean {
	
	@Autowired
	PkgSequenceDao pkgSequenceMapper;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		this.baseDao = pkgSequenceMapper;
	}
	
	@Override
	public byte[] getNextSequence(String cellphone) {
		
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("cellphone", cellphone, QueryExpression.EQUALS);
		List<PkgSequence> result=this.queryByCondition(condition);
		if (result==null||result.size()==0){
			return HexStringUtil.hexStringToBytes("00000000");
		}
		PkgSequence pkgSeq=result.get(0);
		
		int seq=pkgSeq.getCurrentSequence()+1;
		pkgSeq.setCurrentSequence(seq);
		this.updateById(pkgSeq);
		
		String hexString=Integer.toHexString(seq);
		int fillCount = 8-hexString.length();
		
		for(int i=0;i<fillCount;i++){
			hexString = "0"+hexString;
		}
		
		return HexStringUtil.hexStringToBytes(hexString);
		
		
	}
	
	@Override
	public void setCurrentSequence(String cellphone, byte[] sequence) {
		// TODO Auto-generated method stub
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("cellphone", cellphone, QueryExpression.EQUALS);
		List<PkgSequence> result=this.queryByCondition(condition);
		
		int currentSeq = Integer.parseInt(HexStringUtil.bytesToHexString(sequence),16);
		if (result==null||result.size()==0){
			PkgSequence pkgSequence = new PkgSequence(); 
			pkgSequence.setCellphone(cellphone);
			pkgSequence.setCurrentSequence(currentSeq);
			try {
				this.insert(pkgSequence);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			PkgSequence pkgSequence = result.get(0);
			if (pkgSequence.getCurrentSequence()<currentSeq){
				pkgSequence.setCurrentSequence(currentSeq);
				this.updateById(pkgSequence);
			}
		}
		
	}

	@Override
	public int getCurrentSequence(String cellphone) {
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("cellphone", cellphone, QueryExpression.EQUALS);
		List<PkgSequence> result=this.queryByCondition(condition);
		if (result==null||result.size()==0){
			return Integer.MAX_VALUE;
		}else{
			PkgSequence pkgSequence = result.get(0);
			return pkgSequence.getCurrentSequence();
		}
		
		
	}

	

}
